<?php

include('../../include/functions.inc.php');
include('../../include/inputbuilder.inc.php');

if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 's':
            save($db);
            break;
        case 'u':
            update($db);
            break;
        case 'd':
            delete($db);
            break;
    }
}

function save($db) {
    $db->query_insert('cllg_teacher', array(
        'ID' => sqlValue(getParam('ID'), 'text'),
        'FIRST_NAME' => sqlValue(getParam('FIRST_NAME'), 'text'),
        'LAST_NAME' => sqlValue(getParam('LAST_NAME'), 'text'),
        'BIRTHDATE' => sqlValue(getParam('BIRTH_DATE'), 'date'),
        'GENDER' => sqlValue(getParam('GENDER'), 'text'),
        'STATUS' => sqlValue(1, 'int')));
    $fields = unserialize($_SESSION['fields']); //campos dinamicos a guardar					

    foreach ($fields as $fld) {
        $db->query_insert('cllg_table_valuebyfield', array('PK_RECORD' => sqlValue(getParam('ID'), 'text'),
            'VALUE' => sqlValue(getParam($fld), 'text'),
            'FK_TABLEFIELD' => sqlValue($fld, 'text')));
    }

    //echo 'SAVED';
}

function update($db) {
    $db->query_update('cllg_teacher', array(
        'FIRST_NAME' => sqlValue(getParam('FIRST_NAME'), 'text'),
        'LAST_NAME' => sqlValue(getParam('LAST_NAME'), 'text'),
        'BIRTHDATE' => sqlValue(getParam('BIRTH_DATE'), 'date'),
        'GENDER' => sqlValue(getParam('GENDER'), 'text'),
        'STATUS' => sqlValue(1, 'int')), "ID = " . sqlValue(getParam('ID'), 'text'));

    $fields = unserialize($_SESSION['fields']); //campos dinamicos a guardar					
    foreach ($fields as $fld) {
        $r = getFieldValue($db, "cllg_teacher", getParam('ID'), $fld);
        if (count($r) > 0) {
            $db->query_update('cllg_table_valuebyfield', array('VALUE' => sqlValue(getParam($fld), 'text')), 'FK_TABLEFIELD=' . sqlValue($fld, 'text') .
                    ' AND PK_RECORD=' . sqlValue(getParam('ID'), 'text'));
        } else {
            $db->query_insert('cllg_table_valuebyfield', array('PK_RECORD' => sqlValue(getParam('ID'), 'text'),
                'VALUE' => sqlValue(getParam($fld), 'text'),
                'FK_TABLEFIELD' => sqlValue($fld, 'text')));
        }
    }

    //echo 'UPDATED';
}

function delete($db) {
    $db->query_delete('cllg_teacher', 'ID=' . sqlValue(getParam('ID'), 'text'));
    $fields = unserialize($_SESSION['fields']); //campos dinamicos a borrar					
    foreach ($fields as $fld) {
        $db->query_delete('cllg_table_valuebyfield', 'FK_TABLEFIELD=' . sqlValue($fld, 'text')
                . ' AND PK_RECORD=' . sqlValue(getParam('ID'), 'text'));
    }
    //echo 'DELETED';
}

?>